import React, { useEffect,  useState} from 'react';

const IframeAutoFit = ({ iframeId, src }) => {

  const [style, setStyle] = useState({ minHeight: '300px' });
  const [timer, setTimer] = useState(null);
  const [maxCalcCount, setMaxCalcCount] = useState(0); // iframe高度设置一致次数
 
  const iframeOnLoad = () => {
    setTimer(setInterval(() => {
      try {
        const iframe = document.querySelector(`#${iframeId}`)
        // const scrollHeight = iframe.contentWindow.document.body.scrollHeight
        console.log('bodyHeight------', iframe.contentWindow.document.body.scrollHeight);
        // eslint-disable-next-line prefer-destructuring
        const scrollHeight = iframe.contentWindow.document.querySelector('#app div').scrollHeight
        if (style.minHeight === `${scrollHeight}px`) {
          setMaxCalcCount(maxCalcCount + 1)
          if (maxCalcCount > 10) {
            clearInterval(timer)
          }
          return
        }
        console.log('scrollHeight======', scrollHeight);
        setStyle({minHeight: `${scrollHeight}px`})
      } catch (e) {
        //
        console.log('进来了', e);
      }
    }, 1000))
  };

  useEffect(() => {
    const iframe = document.querySelector(`#${iframeId}`)
    // 处理兼容行问题
    if (iframe.attachEvent) {
      iframe.attachEvent('onload', () => {
        // iframe加载完毕以后执行操作
        iframeOnLoad()
      })
    } else {
      iframe.onload = () => {
        // iframe加载完毕以后执行操作
        iframeOnLoad()
      }
    }
    return () => { 
      setMaxCalcCount(0)
      clearInterval(timer)
    }
  },[]);

  return (
    <iframe
      id={iframeId}
      className="fo-iframe"
      name="mainIframe"
      src={src}
      frameBorder="0"
      scrolling="no"
      style={{ width: '100%', ...style }}
      title="Exploerer"
    />
  );
}

export default IframeAutoFit;

